// 元素点击事件
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.categories ul li a').forEach(link => {
        link.addEventListener('click', function() {
            if (this.classList.contains('active')) {
                this.classList.remove('active');
            } else {
                document.querySelectorAll('.categories ul li a').forEach(link => {
                    link.classList.remove('active');
                });
                this.classList.add('active');
            }
        });
    });
});

// 窗口运行完毕，显示商品
window.onload = function () {
    const nicknameElement = document.querySelector('#user');
    const nickname = sessionStorage.getItem('nickname');
    if (nickname) {
        nicknameElement.textContent = nickname;
    } else {
        nicknameElement.textContent = "登录|注册";
    }
    getGoods(0);
}


// 显示商品信息
function getGoods(value){
    $.ajax({
        url: "/goods",
        method: "get",
        data: {num: 4,type: value},
        dataType: "json",
        success: function(dataString) {
            show(dataString);
        }
    })
}

// 显示分类商品
let lastClickedId =null;
document.querySelectorAll('.category-link').forEach(function(link) {
    link.addEventListener('click', function(event) {
        event.preventDefault(); // 阻止默认的链接跳转行为
        const id = this.getAttribute('data-id');

        if (lastClickedId === id) {
            getGoods(0);
        } else {
            getGoods(id);
        }
        lastClickedId = id;
    });
});
